package com.uzai.console.service.wxqcontactrefresh.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.tborder.TbOrderDownloadDto;
import com.uzai.console.dto.feign.tborder.TbOrderRefundDownloadDto;
import com.uzai.console.dto.rocketmq.wxgroup.GetGroupMemberListDto;
import com.uzai.console.dto.wxqcontactrefresh.WxqContactRefreshIdDto;
import com.uzai.console.dto.wxqcontactrefresh.WxqContactRefreshIdListDto;
import com.uzai.console.dto.wxqcontactrefresh.WxqContactRefreshQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.DeviceWxworkInfo;
import com.uzai.console.entity.WxqContactRefresh;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.DeviceWxworkInfoMapper;
import com.uzai.console.mapper.WxqContactRefreshMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.TbOrderFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.wxqcontactrefresh.WxqContactRefreshService;
import com.uzai.console.vo.wxqcontactrefresh.WxqContactRefreshVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信群通讯录刷新
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxqContactRefreshServiceImpl implements WxqContactRefreshService {

    Logger logger = LoggerFactory.getLogger(WxqContactRefreshServiceImpl.class);

    @Autowired
    private WxqContactRefreshMapper wxqContactRefreshMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;

    /**
     * 查询微信群通讯录刷新列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqContactRefreshQuery
     * @return null
     */
    public Page<WxqContactRefreshVo> findWxqContactRefreshList(WxqContactRefreshQuery wxqContactRefreshQuery){

        //新建返回到页面的LIST对象
        List<WxqContactRefreshVo> wxqContactRefreshInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqContactRefresh> page = new Page<>();
        wxqContactRefreshQuery.convert(page);
        List<WxqContactRefresh> wxqContactRefreshList = wxqContactRefreshMapper.findByList(page, wxqContactRefreshQuery);
        if(wxqContactRefreshList != null){
            for (WxqContactRefresh wxqContactRefresh : wxqContactRefreshList){
                WxqContactRefreshVo wxqContactRefreshVo = new WxqContactRefreshVo();
                BeanUtils.copyProperties(wxqContactRefresh, wxqContactRefreshVo);
                if(wxqContactRefreshVo.getDeviceUniqueId() != null){
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getDeviceType(), wxqContactRefresh.getMerId());
                    if(device != null){
                        wxqContactRefreshVo.setDeviceName(device.getDeviceName());
                        wxqContactRefreshVo.setDeviceRemark(device.getDeviceRemark());
                    }
                }
                wxqContactRefreshInfoVoList.add(wxqContactRefreshVo);
            }
        }
        //返回到页面分页对象
        Page<WxqContactRefreshVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wxqContactRefreshInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询微信群通讯录刷新详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqContactRefreshIdDto
     * @return null
     */
    public WxqContactRefreshVo findWxqContactRefresh(WxqContactRefreshIdDto wxqContactRefreshIdDto){
        //返回到页面的VO对象
        WxqContactRefreshVo wxqContactRefreshVo = new WxqContactRefreshVo();

        if(wxqContactRefreshIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        WxqContactRefresh wxqContactRefresh = wxqContactRefreshMapper.selectById(wxqContactRefreshIdDto.getId(), wxqContactRefreshIdDto.getMerId());

        if(wxqContactRefresh == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(wxqContactRefresh, wxqContactRefreshVo);

        if(wxqContactRefreshVo.getDeviceUniqueId() != null){
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getDeviceType(), wxqContactRefresh.getMerId());
            if(device != null){
                wxqContactRefreshVo.setDeviceName(device.getDeviceName());
                wxqContactRefreshVo.setDeviceRemark(device.getDeviceRemark());
            }
        }

        return  wxqContactRefreshVo;
    }


    /**
     * 删除微信群通讯录刷新
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqContactRefreshIdListDto
     * @return null
     */
    public void batchDeleteWxqContactRefresh(WxqContactRefreshIdListDto wxqContactRefreshIdListDto){

        if(wxqContactRefreshIdListDto.getIdList() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id列表");
        }

        wxqContactRefreshMapper.batchDelete(wxqContactRefreshIdListDto.getIdList());
    }

    /**
     * 更新微信通讯录刷新
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void updateWxqContactRefresh(WxqContactRefreshIdDto wxqContactRefreshIdDto){
        if(wxqContactRefreshIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        WxqContactRefresh wxqContactRefresh = wxqContactRefreshMapper.selectById(wxqContactRefreshIdDto.getId(), wxqContactRefreshIdDto.getMerId());

        if(wxqContactRefresh == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //失败状态
        if(wxqContactRefresh.getStatus().intValue() != 3){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该任务状态不是失败状态");
        }

        //更新此任务为未开始状态
        int now = DateUtil.getNowTime();
        wxqContactRefresh.setStatus(0); //未开始
        wxqContactRefresh.setCreateTime(now);
        wxqContactRefresh.setSendTime(0);
        wxqContactRefreshMapper.updateById(wxqContactRefresh);
    }

    /**
     * 批量更新微信通讯录刷新
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqContactRefreshIdListDto
     * @return null
     */
    public void batchUpdateWxqContactRefresh(WxqContactRefreshIdListDto wxqContactRefreshIdListDto){
        if(wxqContactRefreshIdListDto.getIdList() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id列表");
        }

        for (Long id : wxqContactRefreshIdListDto.getIdList()) {
            try {
                WxqContactRefreshIdDto wxqContactRefreshIdDto = new WxqContactRefreshIdDto();
                wxqContactRefreshIdDto.setId(id);
                wxqContactRefreshIdDto.setMerId(wxqContactRefreshIdListDto.getMerId());
                updateWxqContactRefresh(wxqContactRefreshIdDto);
            }catch (Exception e){
                logger.error("批量更新微信通讯录任务失败，error={}", e.getMessage());
            }
        }
    }


    /**
     * 微信群通讯录刷新
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqContactRefresh
     * @return null
     */
    public void autoWxqContactRefresh(WxqContactRefresh wxqContactRefresh){

        if(wxqContactRefresh == null){
            return;
        }

        try {

            int now = DateUtil.getNowTime();

            //刷新通讯录
            if(Tools.getInteger(wxqContactRefresh.getType()).intValue() == 0){
                //个人微信
                if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(wxqContactRefresh.getDeviceType())){
                    DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getMerId());
                    if(deviceWechatInfo != null){
                        //发送MQ消息
                        MsgDto<Object> msgDto = new MsgDto<>();
                        msgDto.setContent(null);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                        msgDto.setDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId());
                        msgDto.setMerId(wxqContactRefresh.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
                        noticeMsgPushProducerService.updateWxContacts(msgDto);

                        //修改机器人更新通讯录时间
                        deviceWechatInfoMapper.updateRefreshWxcontactsTime(deviceWechatInfo.getId(), now);
                    }
                }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(wxqContactRefresh.getDeviceType())){ //企业微信
                    DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getMerId());
                    if(deviceWxworkInfo != null){
                        //发送MQ消息
                        MsgDto<Object> msgDto = new MsgDto<>();
                        msgDto.setContent(null);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                        msgDto.setDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId());
                        msgDto.setMerId(wxqContactRefresh.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
                        noticeMsgPushProducerService.updateWxContacts(msgDto);
                        //保存更新通讯录时间
                        deviceWxworkInfoMapper.updateRefreshWxcontactsTime(deviceWxworkInfo.getId(), now);
                    }
                }
            }else if(Tools.getInteger(wxqContactRefresh.getType()).intValue() == 1){ //刷新群列表
                //个人微信
                if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(wxqContactRefresh.getDeviceType())){
                    DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getMerId());
                    if(deviceWechatInfo != null){
                        //发送MQ消息
                        MsgDto<Object> msgDto = new MsgDto<>();
                        msgDto.setContent(null);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                        msgDto.setDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId());
                        msgDto.setMerId(wxqContactRefresh.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_LIST_REQ.getValue());
                        noticeMsgPushProducerService.updateWxContacts(msgDto);

                        //修改机器人更新通讯录时间
                        deviceWechatInfoMapper.updateRefreshWxcontactsTime(deviceWechatInfo.getId(), now);
                    }
                }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(wxqContactRefresh.getDeviceType())){ //企业微信
                    DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqContactRefresh.getDeviceUniqueId(), wxqContactRefresh.getMerId());
                    if(deviceWxworkInfo != null){
                        //发送MQ消息
                        MsgDto<Object> msgDto = new MsgDto<>();
                        msgDto.setContent(null);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                        msgDto.setDeviceUniqueId(wxqContactRefresh.getDeviceUniqueId());
                        msgDto.setMerId(wxqContactRefresh.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_LIST_REQ.getValue());
                        noticeMsgPushProducerService.updateWxContacts(msgDto);
                        //保存更新通讯录时间
                        deviceWxworkInfoMapper.updateRefreshWxcontactsTime(deviceWxworkInfo.getId(), now);
                    }
                }
            }

            //修改任务状态为进行中
            wxqContactRefresh.setStatus(1);//进行中
            wxqContactRefresh.setSendTime(now);
            wxqContactRefresh.setUpdateTime(now);
            wxqContactRefreshMapper.updateById(wxqContactRefresh);

        }catch (Exception e){
            e.printStackTrace();
            logger.error("-微信群通讯录刷新失败--error={}", e.getMessage());
        }
    }

}
